package com.febs.common.domain;

import com.febs.common.enums.CodeMsgEnum;
import com.febs.common.utils.HttpContextUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

import javax.servlet.http.HttpServletResponse;

import lombok.Builder;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/6/22
 */
@Builder
public class ResponseBo extends HashMap<String, Object> {

    private static final long serialVersionUID = -8713837118340960775L;

    /**
     * 超频
     */
    private static final Integer OVERCLOCKING = 666;

    private static final String CODE = "code";

    private static final String MESSAGE = "message";

    public ResponseBo() {
        put(CODE, CodeMsgEnum.SUCCESS.getCode());
        put(MESSAGE, CodeMsgEnum.SUCCESS.getMessage());
    }

    public static ResponseBo error(Object msg) {
        ResponseBo responseBo = new ResponseBo();
        responseBo.put(CODE, CodeMsgEnum.FAIL.getCode());
        responseBo.put(MESSAGE, msg);
        return responseBo;
    }

    public static ResponseBo error(Object code, Object msg) {
        ResponseBo responseBo = new ResponseBo();
        responseBo.put(CODE, code);
        responseBo.put(MESSAGE, msg);
        return responseBo;
    }

    public static ResponseBo warn(Object msg) {
        ResponseBo responseBo = new ResponseBo();
        responseBo.put(CODE, CodeMsgEnum.DB_RESOURCE_NULL.getCode());
        responseBo.put(MESSAGE, msg);
        return responseBo;
    }

    public static ResponseBo ok(Object msg) {
        ResponseBo responseBo = new ResponseBo();
        responseBo.put(CODE, CodeMsgEnum.SUCCESS.getCode());
        responseBo.put(MESSAGE, msg);
        return responseBo;
    }

    public static ResponseBo unAuthorized(Object msg) {
        ResponseBo responseBo = new ResponseBo();
        responseBo.put(CODE, CodeMsgEnum.UNAUTHORIZED.getCode());
        responseBo.put(MESSAGE, msg);
        return responseBo;
    }

    public static ResponseBo overClocking(Object msg) {
        ResponseBo responseBo = new ResponseBo();
        responseBo.put(CODE, OVERCLOCKING);
        responseBo.put(MESSAGE, msg);
        return responseBo;
    }

    public static void writer(Object code, Object msg) {
        HttpServletResponse response = HttpContextUtils.getResponse();
        response.setCharacterEncoding(String.valueOf(StandardCharsets.UTF_8));
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().print(error(code, msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ResponseBo ok() {
        return new ResponseBo();
    }

    public static ResponseBo error() {
        return ResponseBo.error("");
    }

    @Override
    public ResponseBo put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}
